package com.qezhhnjy.cloud.common.pool.config;

import com.qezhhnjy.cloud.common.pool.conn.Conn;
import com.qezhhnjy.cloud.common.pool.factory.PoolFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhaoyangfu - 2020/8/20 15:18
 */
@Configuration
public class PoolConfig {

    @Bean
    public GenericObjectPoolConfig<Conn> config() {
        GenericObjectPoolConfig<Conn> config = new GenericObjectPoolConfig<>();
        config.setMaxIdle(5);
        config.setMinIdle(1);
        config.setMaxTotal(10);

        // 逐出连接的最小空闲时间
        config.setMinEvictableIdleTimeMillis(6000);
        // 逐出扫描的时间间隔,如果为负数,则不运行逐出线程,默认-1
        config.setTimeBetweenEvictionRunsMillis(3000);
        // 在获取对象的时间检查有效性,默认false
        config.setTestOnBorrow(true);
        // 在归还对象的时候检查有效性
        config.setTestOnReturn(false);
        // 在空闲时检查有效性,默认false
        config.setTestWhileIdle(true);
        // 最大等待时间,默认的值为-1,表示无限等待
        config.setMaxWaitMillis(5);
        // 是否启用后进先出,默认true
        config.setLifo(true);
        // 连接耗尽时是否阻塞,false报异常,true阻塞直到超时,默认true
        config.setBlockWhenExhausted(true);
        // 每次逐出检查时,逐出的最大数目, 默认为3
        config.setNumTestsPerEvictionRun(3);
        return config;
    }

    @Bean
    public PoolFactory factory() {
        return new PoolFactory();
    }

    @Bean
    public GenericObjectPool<Conn> connPool(PoolFactory factory, GenericObjectPoolConfig<Conn> config) {
        return new GenericObjectPool<>(factory, config);
    }

}
